﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team - cellcloudproject@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "CellApp.h"
#include "CellConsole.h"
#include <boost/program_options.hpp>

extern cell::Application* gApp;

namespace cell
{

//-----------------------------------------------------------------------
Application::Application(int argc, char *argv[])
	: mNucleus(NULL)
	, mConsoleMode(true)
	, mConsole(NULL)
{
	std::cout << "Cell Cloud " << CELL_VERSION_MAJOR << "." <<
		CELL_VERSION_MINOR << "." << CELL_VERSION_REVISION <<
	#if CELL_ARCH_TYPE == CELL_ARCHITECTURE_32
		" (Build 32bit "
	#elif CELL_ARCH_TYPE == CELL_ARCHITECTURE_64
		" (Build 64bit "
	#else
		" (Build ? "
	#endif
		<< CELL_VERSION_SUFFIX << " - " << CELL_VERSION_NAME << ")" << std::endl;

	// ASCII Logo
	std::cout << " ___ ___ __  __     ___ __  ___ _ _ ___" << std::endl
			<< "| __| __| | | |    | __| | |   | | | _ \\" << std::endl
			<< "| |_| _|| |_| |_   | |_| |_| | | | | | |" << std::endl
			<< "|___|___|___|___|  |___|___|___|___|___/" << std::endl << std::endl;

	std::cout << "Copyright (c) 2009,2012 Cell Cloud Team, www.cellcloud.net" << std::endl;
	std::cout << "-----------------------------------------------------------------------" << std::endl;

	constructor(argc, argv);
}
//-----------------------------------------------------------------------
Application::~Application(void)
{
	shutdown();
}
//-----------------------------------------------------------------------
void Application::constructor(int argc, char *argv[])
{
	namespace po = boost::program_options;

	po::options_description desc("Cell allowed options");
	desc.add_options()
		("help,h", "Cell help message.")
		("tp", po::value<uint>(), "Bind talk service port.");

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (vm.count("help"))
	{
		std::cout << desc;
		return;
	}

	// Load nucleus property
	NucleusProperty nucleusProp;
	loadProperty(nucleusProp, "nucleus.xml");

	// Create nucleus
	NucleusConfig config;
	config.role = nucleusProp.role;
	mNucleus = CELL_NEW Nucleus(config, "cell.log");

	TalkService::getSingleton().setPort(nucleusProp.talkPort);

	if (vm.count("tp"))
	{
		TalkService::getSingleton().setPort(vm["tp"].as<uint>());
	}
}
//-----------------------------------------------------------------------
bool Application::startup(void)
{
	if (NULL == mNucleus)
		return false;

	// Startup the Nucleus
	if (!mNucleus->startup())
		return false;

#if CELL_PLATFORM == CELL_PLATFORM_WIN32
#ifndef _WINDOWS
	String title = "Cell - " + TAG_TO_STRING(Nucleus::getSingleton().getTag());
	SetConsoleTitle(title.c_str());
	SetConsoleCtrlHandler(ConsoleHandler, TRUE);
	/*HWND hWnd = FindWindow("ConsoleWindowClass", title.c_str());
	if (hWnd)
	{
		ShowWindow(hWnd, SW_HIDE);
	}*/
#endif // _WINDOWS
#endif // CELL_PLATFORM == CELL_PLATFORM_WIN32
	return true;
}
//-----------------------------------------------------------------------
void Application::run(void)
{
	mSpinning = true;

	if (mConsoleMode)
	{
		mConsole = CELL_NEW Console(this);
		while (mSpinning)
		{
			if (!mConsole->processInput(mConsole->waitInput()))
			{
				mSpinning = false;
			}
		}
		CELL_DELETE mConsole;
		mConsole = NULL;
	}
	else
	{
		while (mSpinning)
		{
		#if CELL_PLATFORM == CELL_PLATFORM_WIN32
			Sleep(1000);
		#else
			sleep(1);
		#endif
		}
	}
}
//-----------------------------------------------------------------------
void Application::stop(void)
{
	mSpinning = false;

	if (NULL != mConsole)
	{
		mConsole->interruptInput();
	}
}
//-----------------------------------------------------------------------
void Application::shutdown(void)
{
	if (NULL != mNucleus)
	{
		mNucleus->shutdown();

		CELL_DELETE mNucleus;
		mNucleus = NULL;
	}

	if (NULL != mConsole)
	{
		CELL_DELETE mConsole;
		mConsole = NULL;
	}
}
//-----------------------------------------------------------------------
void Application::loadProperty(NucleusProperty& property, const String& filename)
{
	PropertyFile* propFile = CELL_NEW PropertyFile(filename);

	if (propFile->load())
	{
		// 配置加载成功
		property = propFile->getNucleusProperty();
	}

	CELL_DELETE propFile;
}


#if CELL_PLATFORM == CELL_PLATFORM_WIN32

//---------------------------------------------------------------------------
BOOL WINAPI ConsoleHandler(DWORD event)
{
	switch (event)
	{
	case CTRL_CLOSE_EVENT:
	{
		gApp->stop();
		gApp->shutdown();
		break;
	}
	case CTRL_C_EVENT:
	case CTRL_BREAK_EVENT:
	{
		gApp->stop();
		break;
	}
	default:
		break;
	}
	
	return TRUE;
}

#pragma comment(lib, "Dbghelp.lib")

//---------------------------------------------------------------------------
LONG WINAPI DefaultUnhandledFilter(struct _EXCEPTION_POINTERS *lpExceptionInfo)
{
	LONG ret = EXCEPTION_EXECUTE_HANDLER;

	TCHAR szFileName[64] = {0x0};
	SYSTEMTIME st;
	::GetLocalTime(&st);
	wsprintf(szFileName, TEXT("%04d-%02d-%02d-%02d-%02d-%02d-%02d-%02d.dmp"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, rand()%100);

	HANDLE hFile = ::CreateFile(szFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile != INVALID_HANDLE_VALUE)
	{
		MINIDUMP_EXCEPTION_INFORMATION ExInfo;

		ExInfo.ThreadId = ::GetCurrentThreadId();
		ExInfo.ExceptionPointers = lpExceptionInfo;
		ExInfo.ClientPointers = TRUE;

		// write the dump

		MINIDUMP_TYPE MiniDumpWithDataSegs = static_cast<MINIDUMP_TYPE>(MiniDumpNormal
			| MiniDumpWithHandleData
			| MiniDumpWithUnloadedModules
			| MiniDumpWithIndirectlyReferencedMemory
			| MiniDumpScanMemory
			| MiniDumpWithProcessThreadData
			| MiniDumpWithThreadInfo);

		BOOL bOK = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpWithDataSegs, &ExInfo, NULL, NULL);

		if (bOK)
		{
			printf("Cell : Create Dump File Success!/n");
		}
		else
		{
			printf("Cell : MiniDumpWriteDump Failed: %d/n", GetLastError());
		}

		::CloseHandle(hFile);
	}
	else
	{
		printf("Cell : Create File %s Failed %d/n", szFileName, GetLastError());
	}
	return ret;
}

#ifdef _M_IX86
//-----------------------------------------------------------------------
void DisableSetUnhandledExceptionFilter()
{
	void *addr = (void*)GetProcAddress(LoadLibrary(("kernel32.dll")), "SetUnhandledExceptionFilter");

	if (addr)
	{
		unsigned char code[16];

		int size = 0;

		code[size++] = 0x33;
		code[size++] = 0xC0;
		code[size++] = 0xC2;
		code[size++] = 0x04;
		code[size++] = 0x00;

		DWORD dwOldFlag, dwTempFlag;

		VirtualProtect(addr, size, PAGE_READWRITE, &dwOldFlag);
		WriteProcessMemory(GetCurrentProcess(), addr, code, size, NULL);
		VirtualProtect(addr, size, dwOldFlag, &dwTempFlag);
	}
}
#endif // _M_IX86

#endif

} // end namespace cell
